package com.derbysoft.lowcostadapter.web.action.admin.reservation;

import com.derbysoft.common.web.struts2.support.PaginateActionSupport;
import com.derbysoft.lowcostadapter.commons.model.ReservationDetail;
import com.derbysoft.lowcostadapter.commons.model.ReservationLog;
import com.derbysoft.lowcostadapter.commons.repository.ReservationDetailRepository;
import com.derbysoft.lowcostadapter.commons.repository.ReservationLogRepository;
import com.derbysoft.lowcostadapter.commons.repository.ReservationRepository;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class ReservationAction extends PaginateActionSupport {

    @Autowired
    private ReservationRepository reservationRepository;

    @Autowired
    private ReservationDetailRepository reservationDetailRepository;

    @Autowired
    private ReservationLogRepository reservationLogRepository;

    private ReservationCondition condition;

    private List<ReservationDetail> reservationDetails;

    @Action("list")
    public String list() {
        ActionContext.getContext().setLocale(ServletActionContext.getRequest().getLocale());
        reservationRepository.findByCondition(condition, getPaginater());
        return SUCCESS;
    }

    @Actions({@Action("view-ajax"), @Action("view")})
    public String view() {
        if (StringUtils.isBlank(condition.getErsp())) {
            return INPUT;
        }

        for (ReservationLog reservationLog : reservationLogRepository.findByErsp(condition.getErsp())) {
            getReservationDetails().addAll(reservationDetailRepository.find(reservationLog));
        }
        return SUCCESS;
    }

    public ReservationCondition getCondition() {
        return condition;
    }

    public void setCondition(ReservationCondition condition) {
        this.condition = condition;
    }

    public List<ReservationDetail> getReservationDetails() {
        if (reservationDetails == null) {
            reservationDetails = new ArrayList<ReservationDetail>();
        }
        return reservationDetails;
    }

    public void setReservationDetails(List<ReservationDetail> reservationDetails) {
        this.reservationDetails = reservationDetails;
    }
}